package com.itheima.reggie.controller;

import com.alibaba.fastjson.util.IOUtils;
import com.itheima.reggie.common.R;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
//    从配置文件中读取下载路径
    @Value("${reggie.path}")
    private String uploadPath;

    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());

        //通过MultipartFil获取文件属性（这里获取文件名）,再获取不同文件的后缀
        String filename = file.getOriginalFilename();
        String lastname = filename.substring(filename.lastIndexOf("."));

        //使用时间防止文件重名覆盖（一秒钟上传一次）
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String localTimeName = pattern.format(LocalDateTime.now()).toString()+lastname;

        //指定文件夹不存在时创建
        File dir = new File(uploadPath);
        if (!dir.exists()){
            dir.mkdirs();
        }


//        将上传得临时文件转存到指定磁盘位置
        try {
            file.transferTo(new File(uploadPath+localTimeName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(localTimeName);
    }

    //文件下载（下载到页面进行展示）
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        //设置响应为图片格式
        response.setContentType("image/jpeg");

        try {
            //读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(uploadPath+name));
            //回写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //可以用IOUtils工具类解决
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
